package com.kzd.gtgame.main.mine

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.LifecycleOwner
import com.kzd.gtgame.R
import com.kzd.gtgame.custom.setTransitionStatus
import com.kzd.gtgame.jetpack.vm.AddressViewModel
import com.module.lemlin.http.Status
import com.module.lemlin.owner.OwnerViewModeActivity
import kotlinx.android.synthetic.main.activity_mine_address.*

class MineAddressActivity : OwnerViewModeActivity<AddressViewModel>() {

    override fun viewModel(): AddressViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.activity_mine_address

    override fun stateBar(): StatusBar {
        return StatusBar(color = R.color.white, view = flMineAddressBar)
    }

    override fun initView() {
        supportFragmentManager(AddressListFragment.newInstance(), isToBackStack = false)
    }

    override fun initViewMode() {
        viewModel.addressInfoLiveData.observe(this as LifecycleOwner, { action ->
            supportFragmentManager(AddressEditFragment.newInstance(action))
        })

        viewModel.userAddressKeepLiveData.observe(this as LifecycleOwner, { response ->
            this.setTransitionStatus(response)
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            viewModel.userAddress()
            onBackPressed()
        })
    }

    private fun supportFragmentManager(fragment: Fragment, isToBackStack: Boolean = true) {
        val transaction: FragmentTransaction = supportFragmentManager.beginTransaction()
        if (isToBackStack) {
            transaction.setCustomAnimations(
                R.animator.slide_right_in, R.animator.slide_left_out,
                R.animator.slide_left_in, R.animator.slide_right_out
            )
            transaction.replace(R.id.flMineAddressBody, fragment)
            transaction.addToBackStack(null)
        } else {
            transaction.replace(R.id.flMineAddressBody, fragment)
        }
        transaction.commit()
    }
}